/**
 * author:Administrator
 * date:2016/3/2
 * desc:TODO
 */
"use strict";

let Router = require('koa-router')
  , __pathPrefix = '/api/v1/user'
  , router = new Router({prefix: __pathPrefix});
module.exports = router.routes();
console.log('router:' + __pathPrefix + ',file=' + __filename);

let koabody = require('koa-better-body')();
let roleService = require('../../ddd/application/roleService.js');
let queryService = require('../../ddd/application/queryService');
let appUtil = require('../../common/appUtil.js');
let FormatOutput = require('../../common/FormatOutput.js');
let FormatError = require('../../common/FormatError.js');

/**
 * 用户 注册
 * name,pwd,userType
 */
router.post('/register', koabody, function*() {
  let fields = this.request.body.fields;
  let name = fields.name;
  let pwd = fields.pwd;

  let result = yield roleService.registerUser(name, pwd);
  this.body = FormatOutput.payloadOrError(result, FormatError.E_register_user);
});

/**
 * 用户登录
 * name,pwd,userType
 */
router.post('/login', koabody, function*() {
  let fields = this.request.body.fields;
  let name = fields.name;
  let pwd = fields.pwd;

  let user = yield roleService.login(name, pwd);
  if (user) {
    let token = user.token = appUtil.genToken(user);
    yield appUtil.saveToken(token, user);
  }
  this.body = FormatOutput.payloadOrError(user, FormatError.E_login);
});
